from rest_framework import serializers
from rest_framework import exceptions
from apps.oaauth.models import OAUser, OADepartment, UserStatusChoices


class LoginSerializer(serializers.Serializer):
    email = serializers.EmailField(required=True, error_messages={"required": "请输入邮箱!"})
    password = serializers.CharField(max_length=20, min_length=6)

    def validate(self, attrs):
        email = attrs.get('email')
        password = attrs.get('password')

        if email and password:
            user = OAUser.objects.filter(email=email).first()
            if not user:
                raise serializers.ValidationError("请输入正确的邮箱!")
            if not user.check_password(password):
                raise serializers.ValidationError("请输入正确的密码!")

            if user.status == UserStatusChoices.UNACTIVE:
                raise serializers.ValidationError("用户未激活, 联系管理员激活!")
            if user.status == UserStatusChoices.LOCKED:
                raise serializers.ValidationError("用户被锁定, 联系管理员解锁!")
            # 传给视图函数
            attrs["user"] = user
        else:
            raise serializers.ValidationError("请输入邮箱和密码!")
        return attrs


class DepartmentSerializer(serializers.ModelSerializer):
    class Meta:
        model = OADepartment
        fields = '__all__'


class UserSerializer(serializers.ModelSerializer):
    department = DepartmentSerializer()

    class Meta:
        model = OAUser
        # fields = "__all__"
        exclude = ('password', 'groups', 'user_permissions')


class RestPwdSerializer(serializers.Serializer):
    oldPwd = serializers.CharField(max_length=20, min_length=6)
    newPwd1 = serializers.CharField(max_length=20, min_length=6)
    newPwd2 = serializers.CharField(max_length=20, min_length=6)

    def validate(self, attrs):
        old_password = attrs.get('oldPwd')
        new_password1 = attrs.get('newPwd1')
        new_password2 = attrs.get('newPwd2')

        user = self.context['request'].user
        if not user.check_password(old_password):
            raise exceptions.ValidationError("旧密码错误！")
        if new_password1 != new_password2:
            raise exceptions.ValidationError("两个新密码不一致！")

        return attrs
